/*
 * Copyright (C) 2004, Velocityme Partnership
 * AnchorActions.java
 *
 * Created on 25 November 2004, 07:49
 */

package com.velocityme.www.interfaces.nodeactions;

import com.velocityme.entity.Anchor;
import com.velocityme.entity.Contactable;
import com.velocityme.session.AnchorLocal;
import com.velocityme.session.ContactableLocal;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import com.velocityme.session.TaskLocal;
import com.velocityme.www.actionforms.nodeactionforms.AnchorActionForm;
import com.velocityme.www.dto.IdName;
import com.velocityme.www.utility.NodeUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.tree.TreeModel;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author  Robert
 */
public class AnchorActions extends TaskActions {

    /** Creates a new instance of AnchorActions */
    public AnchorActions() {
    }

    @Override
    public ActionForward show(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Anchor anchor = lookupAnchorBean().findAnchor(key, nodeId);
        session.setAttribute("anchor", anchor);
        session.setAttribute("anchorHistory", lookupNodeBean().getHistory(key, anchor));
        return mapping.findForward("ACTION_DISPLAY");
    }

    @Override
    public ActionForward showCreate(ActionMapping mapping,
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        session.setAttribute("priorityPairs", NodeUtil.getInstance().getPriorityPairs());
        session.setAttribute("allContactablePairs", NodeUtil.getAllContactablePairs(key));
        AnchorActionForm anchorAF = new AnchorActionForm();
        anchorAF.setOwnerId(key.getPerson().getId());
        anchorAF.setInterested(true);
        anchorAF.setDate(Calendar.getInstance());
        session.setAttribute("anchorAF", anchorAF);
        Anchor anchor = new Anchor();
        anchor.setParentNode(lookupNodeBean().findNode(key, nodeId));
        session.setAttribute("anchor", anchor);
        session.setAttribute("years", NodeUtil.getInstance().getYears());
        session.setAttribute("months", NodeUtil.getInstance().getMonths());
        session.setAttribute("days", NodeUtil.getInstance().getDays());
        return mapping.findForward("ACTION_EDIT");
    }

    @Override
    public ActionForward showEdit(ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Anchor anchor = lookupAnchorBean().findAnchor(key, nodeId);
        session.setAttribute("anchor", anchor);
        AnchorActionForm anchorAF = new AnchorActionForm();
        anchorAF.setOwnerId(anchor.getOwner().getId());
        Calendar date = Calendar.getInstance();
        date.setTime(anchor.getStartDate());
        anchorAF.setDate(date);
        session.setAttribute("anchorAF", anchorAF);
        session.setAttribute("priorityPairs", NodeUtil.getInstance().getPriorityPairs());
        session.setAttribute("years", NodeUtil.getInstance().getYears());
        session.setAttribute("months", NodeUtil.getInstance().getMonths());
        session.setAttribute("days", NodeUtil.getInstance().getDays());
        session.setAttribute("allContactablePairs", NodeUtil.getAllContactablePairs(key));
        Collection<IdName> interestedContactablePairs = new ArrayList<IdName>();
        for (Contactable contactable: anchor.getInterestedContactables()) {
            interestedContactablePairs.add(new IdName(contactable.getId(), contactable.toString()));
        }
        session.setAttribute("interestedContactablePairs", interestedContactablePairs);
        Collection<IdName> responsibleContactablePairs = new ArrayList<IdName>();
        for (Contactable contactable: anchor.getResponsibleContactables()) {
            responsibleContactablePairs.add(new IdName(contactable.getId(), contactable.toString()));
        }
        session.setAttribute("responsibleContactablePairs", responsibleContactablePairs);
        return mapping.findForward("ACTION_EDIT");
    }

    @Override
    public ActionForward edit(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        Long nodeId;
        if (request.getParameter("btnSubmit").equals("OK")) {
            Anchor anchor = (Anchor)session.getAttribute("anchor");
            ((AnchorActionForm)form).extractAnchor(key, anchor);
            if (anchor.getId() != null) {
                lookupAnchorBean().editAnchor(key, anchor);
            }
            else {
                anchor = lookupAnchorBean().createAnchor(key, anchor, ((AnchorActionForm)form).isInterested());
            }
            nodeId = anchor.getId();
        }
        // Cancel simply displays the original node again
        else {
            nodeId = (Long)session.getAttribute("nodeId");
        }
        request.setAttribute("nodeId", nodeId);
        return mapping.findForward("ACTION_SUCCESS");
    }

    private AnchorLocal lookupAnchorBean() {
        try {
            Context c = new InitialContext();
            return (AnchorLocal) c.lookup("java:comp/env/AnchorBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private NodeLocal lookupNodeBean() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private ContactableLocal lookupContactableBean() {
        try {
            Context c = new InitialContext();
            return (ContactableLocal) c.lookup("java:comp/env/ContactableBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private TaskLocal lookupTaskBean() {
        try {
            Context c = new InitialContext();
            return (TaskLocal) c.lookup("java:comp/env/TaskBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
